package com.groupbuying.orderproducer.service.impl;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.serializer.SerializerFeature;
import com.groupbuying.orderproducer.connector.SysConfigFeign;
import com.groupbuying.orderproducer.constants.CommodityOrderItemEnumConstants;
import com.groupbuying.orderproducer.constants.CommodityOrderMainEnumConstants;
import com.groupbuying.orderproducer.constants.CommonConstants;
import com.groupbuying.orderproducer.context.FilterContextHandler;
import com.groupbuying.orderproducer.dao.CommodityOrderItemDao;
import com.groupbuying.orderproducer.dao.CommodityOrderMainDao;
import com.groupbuying.orderproducer.domain.CommodityOrderItemDO;
import com.groupbuying.orderproducer.domain.CommodityOrderMainDO;
import com.groupbuying.orderproducer.mq.OrderMQConfig;
import com.groupbuying.orderproducer.service.CommodityOrderUshopService;
import com.groupbuying.orderproducer.utils.BeanOrMapConvertUtils;
import com.groupbuying.orderproducer.utils.NumberValidator;
import com.groupbuying.orderproducer.utils.apiresult.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 优店商品订单业务实现类
 *
 * @author m
 */
@Service
@EnableTransactionManagement
public class CommodityOrderUshopServiceImpl implements CommodityOrderUshopService {
    public static final Logger LOGGER = LoggerFactory.getLogger(CommodityOrderUshopServiceImpl.class);

    @Autowired
    private CommodityOrderMainDao commodityOrderMainDao;
    @Autowired
    private CommodityOrderItemDao commodityOrderItemDao;
    @Autowired
    private SysConfigFeign sysConfigFeign;
    @Autowired
    private Producer producer;
    @Value("${Commodity_Order_Config.counterId}")
    private String counterId;


    /**
     * 创建商品订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult crateCommodityOrderService(Map<String, Object> params) {
        //返回参数
        Map<String, Object> map = new HashMap<>();
        try {
            //订单编号
            String id = sysConfigFeign.getOrderID(params.get("cityCode").toString(), params.get("bizCode").toString());
            //用户id
            String uid = FilterContextHandler.getUserID();
            //商品id
            Object tempParam = params.get("skuId");
            String skuId = tempParam == null ? null : tempParam.toString();
            //商品名字
            tempParam = params.get("skuName");
            String skuName = tempParam == null ? null : tempParam.toString();
            //图片地址
            tempParam = params.get("skuImage");
            String skuImage = tempParam == null ? null : tempParam.toString();
            //商品数量
            tempParam = params.get("quantity");
            String quantity = tempParam == null ? null : tempParam.toString();
            //原始单价
            tempParam = params.get("originPrice");
            String originPrice = tempParam == null ? null : tempParam.toString();
            //购买单价
            tempParam = params.get("buyPrice");
            String buyPrice = tempParam == null ? null : tempParam.toString();
            //最终单价
//            tempParam = params.get("presentPrice");
            String presentPrice = buyPrice;
            //最终总金额
            tempParam = params.get("presentTotal");
            String presentTotal = tempParam == null ? null : tempParam.toString();
            //购买总金额
            tempParam = params.get("buyTotal");
            String buyTotal = tempParam == null ? null : tempParam.toString();
            //优惠总金额
//            tempParam = params.get("discountTotal");
            String discountTotal = new BigDecimal(buyTotal).subtract(new BigDecimal(presentPrice)).toString();
            tempParam = params.get("remark");
            String remark = tempParam == null ? null : tempParam.toString();

            if (StringUtils.isEmpty(skuId) || StringUtils.isEmpty(skuName)
                    || StringUtils.isEmpty(skuImage) || StringUtils.isEmpty(quantity) || StringUtils.isEmpty(originPrice)
                    || StringUtils.isEmpty(buyPrice) || StringUtils.isEmpty(presentPrice) || StringUtils.isEmpty(buyTotal) ||
                    StringUtils.isEmpty(discountTotal) || StringUtils.isEmpty(presentTotal)) {

                LOGGER.error("够样优店创建子订单,参数为空!商品id:{},商品名字:{},图片地址:{},商品数量:{},原始单价:{},购买单价:{},最终单价:{},购买总金额:{},优惠总金额:{},最终总金额:{}",
                        skuId, skuName, skuImage, quantity, originPrice, buyPrice, presentPrice, buyTotal, discountTotal, presentTotal);
                return ApiResult.paramIsNull();
            }

            //判断是否是金额
            if (!NumberValidator.isNumber(originPrice)) {
                LOGGER.error("创建商品订单,originPrice无效数字");
                ApiResult.failure();
            }
            if (!NumberValidator.isNumber(buyPrice)) {
                LOGGER.error("创建商品订单,buyPrice无效数字");
                ApiResult.failure();
            }
            if (!NumberValidator.isNumber(buyTotal)) {
                LOGGER.error("创建商品订单,buyTotal无效数字");
                ApiResult.failure();
            }
            if (!NumberValidator.isNumber(discountTotal)) {
                LOGGER.error("创建商品订单,discountTotal无效数字");
                ApiResult.failure();
            }
            if (!NumberValidator.isNumber(presentTotal)) {
                LOGGER.error("创建商品订单,presentTotal无效数字");
                ApiResult.failure();
            }

            //主订单
            CommodityOrderMainDO commodityOrderMainDO = new CommodityOrderMainDO();
            //订单编号
            commodityOrderMainDO.setId(id);
            //删除标记
            commodityOrderMainDO.setIsDelete(CommodityOrderMainEnumConstants.ENUM_ISDELETE_UNDEL);
            //创建时间
            commodityOrderMainDO.setGmtCreate(new Date());
            //更新时间
            //commodityOrderMainDO.setGmtModify(new Date());
            //用户id
            commodityOrderMainDO.setCustomerId(uid);//uid
            //商品总价
            commodityOrderMainDO.setTotalPrice(new BigDecimal(presentPrice));
            //优惠金额
            commodityOrderMainDO.setDiscountPrice(new BigDecimal(discountTotal));
            //物流金额
            commodityOrderMainDO.setLogisticsPrice(new BigDecimal("0"));
            //最终金额
            commodityOrderMainDO.setPresentPrice(new BigDecimal(presentPrice));
            //实付金额
            commodityOrderMainDO.setPayAmount(new BigDecimal(presentTotal));
            //是否退换
            commodityOrderMainDO.setHasReturnExchange(0);
            //备注
            commodityOrderMainDO.setRemark(remark);
            //状态
            commodityOrderMainDO.setOrderState(Integer.valueOf(CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_UNPAY));
            commodityOrderMainDao.save(commodityOrderMainDO);
            LOGGER.info("够样优店商品订单保存成功,主订单id：{}", commodityOrderMainDO.getId());

            //子订单
            String subID = sysConfigFeign.getSuborderId(params.get("cityCode").toString(), params.get("bizCode").toString());
            CommodityOrderItemDO commodityOrderItemDO = new CommodityOrderItemDO();
            //订单子项目ID
            commodityOrderItemDO.setId(subID);
//            commodityOrderItemDO.setId("234534555535345");
            //订单编号
            commodityOrderItemDO.setOrderId(id);
            //物流id
            //commodityOrderItemDO.setOrderLogisticsId("56565");
            //商品id=
            commodityOrderItemDO.setSkuId(skuId);
            //商品名字=
            commodityOrderItemDO.setSkuName(skuName);
            //图片地址=
            commodityOrderItemDO.setSkuImage(skuImage);
            //商品数量
            commodityOrderItemDO.setQuantity(Integer.parseInt(quantity));
            //原始单价=
            commodityOrderItemDO.setOriginPrice(new BigDecimal(originPrice));
            //购买单价
            commodityOrderItemDO.setBuyPrice(new BigDecimal(buyPrice));
            //最终单价
            commodityOrderItemDO.setPresentPrice(new BigDecimal(presentPrice));
            //购买总金额=
            commodityOrderItemDO.setBuyTotal(new BigDecimal(buyTotal));
            //优惠总金额
            commodityOrderItemDO.setDiscountTotal(new BigDecimal(discountTotal));
            //最终总金额
            commodityOrderItemDO.setPresentTotal(new BigDecimal(presentTotal));
            //是否退换货
            commodityOrderItemDO.setHasReturnExchange(0);
            //创建时间
            commodityOrderItemDO.setCreateTime(new Date());
            //更新时间
            commodityOrderItemDO.setUpdateTime(new Date());
            //备注
            commodityOrderItemDO.setRemark(remark);
            //发送方式
            commodityOrderItemDO.setDeliveryType(1);
            //状态
            commodityOrderItemDO.setStatus(Integer.valueOf(CommodityOrderItemEnumConstants.ENUM_STATUS_INIT));
            //删除标记
            commodityOrderItemDO.setIsDelete(CommodityOrderItemEnumConstants.ENUM_ISDELETE_UNDEL);
            commodityOrderItemDao.save(commodityOrderItemDO);
            LOGGER.info("够样优店商品订单保存成功,子订单id：{}", commodityOrderItemDO.getOrderId());

//        发送订单超时mq
//        设置主订单关闭时间
//        commodityOrderItemDO.setClosingTime(new Date(commodityOrderItemDO.getCreateTime().getTime() + CommonConstants.ORDER_OVERDUE));
            try {
                Message message = new Message(OrderMQConfig.TOPIC, OrderMQConfig.COMMODITY_TAG_TIMINGCLOSE,
                        JSON.toJSONString(BeanOrMapConvertUtils.objectToMap(commodityOrderMainDO), SerializerFeature.DisableCircularReferenceDetect).getBytes());
                message.setStartDeliverTime(System.currentTimeMillis() + CommonConstants.ORDER_OVERDUE);
                producer.send(message);
                LOGGER.info("够样优店商品订单定时检测发送MQ成功，主订单号:{}", commodityOrderMainDO.getId());
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.info("够样优店商品订单定时检测发送MQ失败，主订单号:{}", commodityOrderMainDO.getId());
            }

            map.put("id", commodityOrderMainDO.getId());
            map.put("presentTotal", commodityOrderItemDO.getPresentTotal());
            map.put("counterId", counterId);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("商品订单创建有误");
            return ApiResult.failure();
        }
        return ApiResult.success(map);

    }
    //订单id 最终金额

    /**
     * 根据商品id查询订单
     */
    @Override
    public Map<String, ?> getGoodByOrderId(String orderId) {
        LOGGER.info("打印传参商品订单ID:{}", orderId);
        if (StringUtils.isEmpty(orderId)) {
            LOGGER.error("够样优店商品订单查询订单为空!商品id{}", orderId);
            return ApiResult.paramIsNull();
        }
        CommodityOrderMainDO commodityOrderMainDO = commodityOrderMainDao.get(orderId);

        if (commodityOrderMainDO == null) {
            LOGGER.error("够样优店商品订单查询订单信息不存在！");
            return ApiResult.failure("订单信息不存在");
        }
        Map resultMap = new HashMap();
        try {
            resultMap = BeanOrMapConvertUtils.objectToMap(commodityOrderMainDO);
            LOGGER.info("获取商品订单订单成功,订单号:{}", commodityOrderMainDO.getId());
        } catch (Exception e) {
            LOGGER.error("够样优店商品订单查询订单信息返回失败");
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 修改商品主订单状态
     *
     * @param param map参数
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult changeCommodityMainOrderStateService(Map<String, ?> param) {
        LOGGER.info("打印：消费者，修改商品主订单状态，参数：{}", JSON.toJSONString(param));
        //判断参数
        if (param == null) {
            LOGGER.error("商品订单修改状态修改，参数为空");
            return ApiResult.paramIsNull();
        }

        String orderId = param.get("orderId") == null ? null : param.get("orderId").toString();
        if (StringUtils.isEmpty(orderId)) {
            LOGGER.error("商品订单修改状态修改，商品订单id为空");
            return ApiResult.paramIsNull();
        }

        String orderState = param.get("orderState") == null ? null : param.get("orderState").toString();
        if (StringUtils.isEmpty(orderState)) {
            LOGGER.error("商品订单修改状态修改，商品订单状态为空");
            return ApiResult.paramIsNull();
        }

        //查询主订单
        CommodityOrderMainDO mainDO = commodityOrderMainDao.get(orderId);

        if (mainDO == null) {
            LOGGER.error("修改商品订单状态，没有查询到主订单,商品订单id{}", orderId);
            return ApiResult.failure();
        }

        String mainState = mainDO.getOrderState().toString();

        Map<String, Object> mParam = new HashMap<>();
        Map<String, Object> iParam = new HashMap<>();
        //1. 待发货 主订单不是待发、是未支付、已关闭才可以修改
        if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_WAIT_FOR_DELIVERY.equals(orderState)) {
            //商品最终金额
            BigDecimal payAmount = new BigDecimal(param.get("payAmount").toString());

            if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_WAIT_FOR_DELIVERY.equals(mainState)) {
                LOGGER.info("修改商品主订单状态，重复提交，订单状态已是待发货状态，主订单id：{}", orderId);
                return ApiResult.success();
            } else if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_UNPAY.equals(mainState)
                    || CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_CLOSED.equals(mainState)) {
                mParam.put("id", orderId);   //订单id
                mParam.put("orderState", CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_WAIT_FOR_DELIVERY);   //订单状态
                mParam.put("gmtModify", new Date());   //订单修改时间
                mParam.put("paymentTime", new Date());   //支付时间
                mParam.put("payAmount", payAmount);   //实际支付金额
                //金额修改
                //修改主订单
                commodityOrderMainDao.updateById(mParam);

                iParam.put("orderId", mainDO.getId());  //订单id
                iParam.put("updateTime", new Date());  //更新时间
                iParam.put("paymentTime", new Date());  //支付时间
                iParam.put("presentTotal", payAmount);   //实际支付金额
                //金额修改
                iParam.put("status", CommodityOrderItemEnumConstants.ENUM_STATUS_WAIT_FOR_DELIVERY);
                //修改子订单状态
                commodityOrderItemDao.updateByOrderId(iParam);
                LOGGER.info("修改商品主订单状态，待发货状态修改成功，主订单id：{}", orderId);
                return ApiResult.success();
            }
            LOGGER.error("修改商品主订单状态，待发货状态修改有误，主订单id：{}", orderId);
            return ApiResult.failure();
        }

        //2. 关闭状态 不是关闭状态、是待支付状态可以修改
        if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_CLOSED.equals(orderState)) {
            if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_CLOSED.equals(mainState)) {
                LOGGER.info("修改商品主订单状态，重复修改状态，订单状态已是关闭状态，主订单id：{}", orderId);
                return ApiResult.success();
            } else if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_UNPAY.equals(mainState)) {

                mParam.put("id", orderId);   //订单id
                mParam.put("orderState", CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_CLOSED);   //订单状态
                mParam.put("gmtModify", new Date());   //订单修改时间
                //修改主订单
                commodityOrderMainDao.updateById(mParam);

                LOGGER.info("修改商品主订单状态，关闭状态修改成功，主订单id：{}", orderId);
                return ApiResult.success();
            }
            LOGGER.error("修改商品主订单状态，关闭状态修改有误，主订单id：{}", orderId);
            return ApiResult.failure();
        }

        //3. 已完成状态 是待发货状态可以修改
        if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_FINISHED.equals(orderState)) {
            if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_FINISHED.equals(mainState)) {
                LOGGER.info("修改商品主订单状态，重复修改状态，订单状态已是完成状态，主订单id：{}", orderId);
                return ApiResult.success();
            } else if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_WAIT_FOR_DELIVERY.equals(mainState)) {
                mParam.put("id", orderId);   //订单id
                mParam.put("orderState", CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_FINISHED);   //订单状态
                mParam.put("gmtModify", new Date());   //订单修改时间
                mParam.put("closingTime", new Date());   //订单完成时间
                //修改主订单
                commodityOrderMainDao.updateById(mParam);

                iParam.put("orderId", mainDO.getId());  //订单id
                iParam.put("updateTime", new Date());  //更新时间
                iParam.put("receiverTime", new Date());  //收货时间
                iParam.put("status", CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED);    //状态修改
                //修改子订单状态
                commodityOrderItemDao.updateByOrderId(iParam);

                LOGGER.info("修改商品主订单状态，已完成状态修改成功，主订单id：{}", orderId);
                return ApiResult.success();
            }
            LOGGER.error("修改商品主订单状态，已完成状态修改有误，主订单id：{}", orderId);
            return ApiResult.failure();
        }

        LOGGER.error("修改商品订单状态，当前状态有误，子订单id：{},状态：{}", orderId, orderState);
        return ApiResult.failure();
    }

    /**
     * 修改商品子订单状态
     *
     * @param param map参数
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult changeCommodityItemOrderStateService(Map<String, ?> param) {

        LOGGER.info("打印：修改商品子订单状态，参数：{}", JSON.toJSONString(param));
        //商品订单状态
        String orderState = param.get("orderState").toString();
        //商品主订单id
        String orderId = param.get("orderId").toString();

        // 查询子订单信息
        CommodityOrderItemDO itemDO = commodityOrderItemDao.get(orderId);

        if (itemDO == null) {
            LOGGER.error("修改商品子订单状态，没有查询到子订单,商品订单id{}", orderId);
            return ApiResult.failure();
        }

        String itemState = itemDO.getStatus().toString();

        Map<String, Object> iUpdateParam = new HashMap<>();
        Map<String, Object> iSerchParam = new HashMap<>();
        Map<String, Object> mParam = new HashMap<>();
        //1.（主订单与子订单）待发 已发 已收
        //1.1 已发货 不是已发货、是待发货才可修改
//        if (CommodityOrderItemEnumConstants.ENUM_STATUS_DELIVERY.equals(itemState)){
//            if (!CommodityOrderItemEnumConstants.ENUM_STATUS_DELIVERY.equals(itemState)
//                    && CommodityOrderItemEnumConstants.ENUM_STATUS_WAIT_FOR_DELIVERY.equals(itemState)){
//                iUpdateParam.put("id",itemDO.getId());  //子订单id
//                iUpdateParam.put("status",CommodityOrderItemEnumConstants.ENUM_STATUS_DELIVERY);    //状态
//
//                //修改子订单状态
//                commodityOrderItemDao.updateById(iUpdateParam);
//
//                //查询状态数
//                iSerchParam.put("id",orderId);
//                iSerchParam.put("status",CommodityOrderItemEnumConstants.ENUM_STATUS_DELIVERY);
//                iSerchParam.put("is_delete",CommodityOrderItemEnumConstants.ENUM_ISDELETE_UNDEL);
//                int count = commodityOrderItemDao.findOtherStateCount(iSerchParam);
//
//                if (count>0){
//                    mParam.put("id",itemDO.getOrderId());
//                    mParam.put("orderState",CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_DELIVERY);
//                    //修改主订单
//                    commodityOrderMainDao.updateById(mParam);
//                    LOGGER.info("修改商品子订单状态，主订单，已发货状态修改成功，主订单id：{}，子订单id：{}",itemDO.getOrderId(),orderId);
//                }
//
//                LOGGER.info("修改商品子订单状态,已发货状态修改成功，主订单id：{}，子订单id：{}",itemDO.getOrderId(),orderId);
//                return ApiResult.success();
//            }
//            LOGGER.info("修改商品订单状态，已发货状态修改有误，主订单id：{}，子订单id：{}",itemDO.getOrderId(),orderId);
//            return ApiResult.failure();
//        }

        //1.2 已收货(并修改主订单已完成) 不是已收货、是已发货、待发货才可修改
        if (CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED.equals(orderState)) {
            if (CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED.equals(itemState)) {
                LOGGER.info("修改商品子订单状态，重复修改状态，订单状态已是已收货状态，主订单id：{}", orderId);
                return ApiResult.success();
            } else if (CommodityOrderItemEnumConstants.ENUM_STATUS_DELIVERY.equals(itemState)
                    || CommodityOrderItemEnumConstants.ENUM_STATUS_WAIT_FOR_DELIVERY.equals(itemState)) {
                iUpdateParam.put("id", itemDO.getId());
                iUpdateParam.put("status", CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED);
                iUpdateParam.put("receiverTime", new Date());  //收货时间
                iUpdateParam.put("updateTime", new Date());   //订单修改时间

                //修改子订单状态
                commodityOrderItemDao.updateById(iUpdateParam);

                //查询状态数
                iSerchParam.put("orderId", itemDO.getOrderId());
                iSerchParam.put("status", CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED);
                iSerchParam.put("isDelete", CommodityOrderItemEnumConstants.ENUM_ISDELETE_UNDEL);
                int count = commodityOrderItemDao.findOtherStateCount(iSerchParam);

                if (count <= 0) {
                    mParam.put("id", itemDO.getOrderId());
                    mParam.put("orderState", CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_FINISHED);
                    mParam.put("closingTime", new Date());
                    mParam.put("gmtModify", new Date());   //订单修改时间
                    //修改主订单
                    commodityOrderMainDao.updateById(mParam);
                    LOGGER.info("修改商品子订单状态，主订单，已收货状态修改成功，主订单id：{}，子订单id：{}", itemDO.getOrderId(), orderId);
                }
                LOGGER.info("修改商品子订单状态，已收货状态修改成功，主订单id：{}，子订单id：{}", itemDO.getOrderId(), orderId);
                return ApiResult.success();
            }
            LOGGER.error("修改商品子订单状态，已收货状态修改有误，主订单id：{}，子订单id：{}", itemDO.getOrderId(), orderId);
            return ApiResult.failure();
        }

        //2.（体现在子订单）退货 退货中 已退货 换货 换货中 换货成功
        //2.1 退款中 不是退款中、是已收货才可修改
        if (CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNING.equals(orderState)) {
            if (CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNING.equals(itemState)) {
                LOGGER.info("修改商品子订单状态，重复修改状态，订单状态已是退款中状态，主订单id：{}", orderId);
                return ApiResult.success();
            } else if (CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED.equals(itemState)) {
                //修改子订单状态
                iUpdateParam.put("id", itemDO.getId());
                iUpdateParam.put("updateTime", new Date());   //订单修改时间
                iUpdateParam.put("status", CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNING);

                //修改子订单状态
                commodityOrderItemDao.updateById(iUpdateParam);
                LOGGER.info("修改商品子订单状态，退款中状态修改成功，主订单id：{}，子订单id：{}", itemDO.getOrderId(), orderId);
                return ApiResult.success();
            }
            LOGGER.info("修改商品子订单状态，退款中状态修改有误，主订单id：{}，子订单id：{}", itemDO.getOrderId(), orderId);
            return ApiResult.failure();
        }
        //2.2 已退货 不是已退货、是退款中才可修改
        if (CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNED.equals(orderState)) {
            if (CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNED.equals(itemState)) {
                LOGGER.info("修改商品子订单状态，重复修改状态，订单状态已是已退货状态，主订单id：{}", orderId);
                return ApiResult.success();
            } else if (CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNING.equals(itemState)) {

                iUpdateParam.put("id", itemDO.getId());
                iUpdateParam.put("updateTime", new Date());   //订单修改时间
                iUpdateParam.put("status", CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNED);

                //修改子订单状态
                commodityOrderItemDao.updateById(iUpdateParam);
                LOGGER.info("修改商品子订单状态，已退货状态修改成功，子订单id：{}", orderId);
                return ApiResult.success();
            }
            LOGGER.info("修改商品子订单状态，已退货状态修改有误，子订单id：{}", orderId);
            return ApiResult.failure();
        }
        //2.3 换货中 不是换货中、是已收货才可修改
        if (CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGING.equals(orderState)) {
            if (CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGING.equals(itemState)) {
                LOGGER.info("修改商品子订单状态，重复修改状态，订单状态已是换货中状态，主订单id：{}", orderId);
                return ApiResult.success();
            } else if (CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED.equals(itemState)) {
                iUpdateParam.put("id", itemDO.getId());
                iUpdateParam.put("updateTime", new Date());   //订单修改时间
                iUpdateParam.put("status", CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGING);

                //修改子订单状态
                commodityOrderItemDao.updateById(iUpdateParam);
                LOGGER.info("修改商品子订单状态，换货中状态修改成功，子订单id：{}", orderId);
                return ApiResult.success();
            }
            LOGGER.info("修改商品子订单状态，换货中状态修改有误，子订单id：{}", orderId);
            return ApiResult.failure();
        }
        //2.4 换货成功 不是换货成功、是换货中才可修改
        if (CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGED.equals(orderState)) {
            if (CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGED.equals(itemState)) {
                LOGGER.info("修改商品子订单状态，重复修改状态，订单状态已是换货成功状态，主订单id：{}", orderId);
                return ApiResult.success();
            } else if (CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGING.equals(itemState)) {
                iUpdateParam.put("id", itemDO.getId());
                iUpdateParam.put("updateTime", new Date());   //订单修改时间
                iUpdateParam.put("status", CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGED);

                //修改子订单状态
                commodityOrderItemDao.updateById(iUpdateParam);
                LOGGER.info("修改商品子订单状态，换货成功状态修改成功，子订单id：{}", orderId);
                return ApiResult.success();
            }
            LOGGER.error("修改商品子订单状态，换货成功状态修改有误，子订单id：{}", orderId);
            return ApiResult.failure();
        }

        LOGGER.error("修改商品子订单状态，当前状态有误，子订单id：{},状态：{}", orderId, orderState);
        return ApiResult.failure();
    }
}
